using System.Collections.Generic;
using System.Linq;

namespace ORM
{
    public class PersonsList
    {
        private LinkedList<Person> _personsList = new LinkedList<Person>();
        private List<PersonDb> _personsDbList = new List<PersonDb>();

        public int Size { get { return _personsDbList.Count; } }

        private static PersonsList _instance;
        public static PersonsList GetPersonsList()
        {
            return _instance ?? (_instance = new PersonsList());
        }

        private PersonsList()
        {
            if (PersonDb.DBConnection == null) return;
            PersonDb.Connect();
            var arr = PersonDb.MakeAQuery("SELECT ID FROM " + PersonDb.TableName);
            for (var i = 1; i < arr.Length; ++i)
            {
                _personsDbList.Add(new PersonDb(int.Parse(arr[i][0])));
            }
            PersonDb.Disconnect();
        }

        public void RefreshData()
        {
            if (PersonDb.DBConnection == null) return;
            PersonDb.Connect();
            var arr = PersonDb.MakeAQuery("SELECT ID FROM " + PersonDb.TableName);
            int currentId;
            for (var i = 1; i < arr.Length; ++i)
            {
                currentId = int.Parse(arr[i][0]);
                if (!_personsDbList.Any(t => t.Id == currentId))
                    _personsDbList.Add(new PersonDb(currentId));
            }
            PersonDb.Disconnect();
        }

        public Person this[int index]
        {
            get
            {
                if (index < 0 || index >= _personsDbList.Count) return null;
                var person = _personsDbList[index].ObjectLink;
                return person;
            }
        }

        public void Add(Person person)
        {
            var personDb = new PersonDb(person);
            person.DBObject = personDb;
        }

        public void RemoveAt(int index)
        {
            if (this[index] == null) return;
            _personsDbList[index].ObjectLink.Remove();
            _personsDbList[index].Remove();
            _personsDbList.RemoveAt(index);
        }
    }
}